<?php
class PHZ_Room
{
    /**
     * 通过房间ID查找房间信息并进行返回操作
     * @param $room_id
     */
    public static function __getRoomInfo_byID( $room_id , $db_connect ){
        return $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
    }

    /**
     * 删除一个房间
     * @param $room_id
     */
    public static function __deleteRoom( $room_id , $db_connect ){
        return $db_connect->delete('tt_room')->where( "room_id = " . $room_id )->query();
    }

    /**
     * 删除30分钟内未开始或者没进人的房间，包括返回钻石
     * @param $user_id      开房人
     * @param $db_connect   数据连接
     * @opsug 5分钟检测一次;;利用mem做记录;
     */
    public static function __gennerBeOver( $user_id , $db_connect ){
        $roomList = $db_connect->select('*')->from('tt_room')->where("is_daikai = 1 AND room_cid= '". $user_id ."' ")->query();
        if( count( $roomList ) <= 0 ){ return false; }
        foreach ( $roomList as $key => $value ){
            if( (time() - $value['room_time_micor']) >= GENNER_BEOVER_TIME ){
                if( $value['room_status'] == 0 ){
                    if( $value['room_player_1'] == 0 && $value['room_player_2'] == 0 && $value['room_player_3'] == 0 ) {
                        if( $value['consume'] >= 1 ){
                            PHZ_Member::__UserAdd_consume( $user_id , $value['consume'] , $db_connect );//是否需要恢复用户的钻石
                        }
                        PHZ_Room::__deleteRoom( $value['room_id'] , $db_connect );//删除房间信息
                        PHZ_Log::__DeleteRoom_ALLLOG( $value['room_id'] , $db_connect );//删除该房间的所有日志log
                        PHZ_Memcache::__set_RoomInfo_ToMemcache( $value['room_id'] , true );//更新房间缓存信息
                    }
                }
            }
        }
        return true;
    }

    /**
     * 随机生成不重复的房间号(存在的情况下，则无限递归继续重新生产房号)
     */
    public static function __getRandRoomID( $db_connect ){
        $room_id = "";
        for( $i = 1 ; $i <= 5 ; $i++ ){
            $room_id = $room_id .  rand(0,9);
        }
        $room_id = rand(1,9) . $room_id;
        if( self::__getRoomInfo_byID( $room_id , $db_connect ) != false ){
            return self::__getRandRoomID( $db_connect );
        }
        return $room_id;
    }

    /**
     * 通过房间ID查询房间中当前共有几名玩家
     * @param $room_info
     * @return int
     */
    public static function __getRoom_NumberOf( $room_info ){
        $room_number_of = 0;
        foreach ( $room_info as $key => $value ){
            if( strstr($key,'room_player_') != false && $value != 0 ){
                $room_number_of++;
            }
        }
        return $room_number_of;
    }

    /**
     * 用户加入房间,并返回加入后的房间数据
     * @param $room_info
     * @param $user_id
     */
    public static function __Join_inThe_Room( $room_info , $user_id , $db_connect ){
        $room_id = $room_info['room_id'];
        if( $room_info['room_player_1'] == 0 && $room_info['room_player_1'] != $user_id ){//第一个进入房间的人为庄家
            $db_connect->update('tt_room')->cols(array('room_player_1'=> $user_id , 'banker' =>  $user_id ))->where('room_id=' . $room_id )->query();
            $room_info['room_player_1'] = $user_id;
        }else if( $room_info['room_player_2'] == 0 && $room_info['room_player_2'] != $user_id ){
            $db_connect->update('tt_room')->cols(array('room_player_2'=> $user_id ))->where('room_id=' . $room_id )->query();
            $room_info['room_player_2'] = $user_id;
        }else if( $room_info['room_player_3'] == 0 && $room_info['room_player_3'] != $user_id ){
            $db_connect->update('tt_room')->cols(array('room_player_3'=> $user_id ))->where('room_id=' . $room_id )->query();
            $room_info['room_player_3'] = $user_id;
        }
        return $room_info;
    }

    /**
     * 当有用户成功加入后；给所有人发送一个有人加入的LOG信息；此信息也能用于保证重连
     * @param $room_info
     * @param $user_id
     * @param $db_connect
     */
    public static function __Join_Room_sendLog( $room_info , $user_id , $db_connect ){
        $room_id         = $room_info['room_id'];
        $data            = array();
        $data['log_rid'] = $room_id;
        $data['log_jid'] = $room_info['room_js'];
        $data['log_md']  = 14;
        $data['log_uid'] = $user_id;
        foreach( $room_info as $key => $value ){
            if( strstr($key,'room_player_') != false){
                if( $value != 0 ){
                    $data['log_to_uid'] = $value;
                    $temp = array();
                    $temp['pl'] = 1;//游戏操作类型，1：开局
                    $temp['mu'] = $value;
                    $temp['mn'] = PHZ_Member::__getFieldBy_ID( $value , 'name' , $db_connect );
                    $temp['mf'] = "";
                    $temp['xf'] = "";$temp['df'] = "";$temp['sf'] = "";
                    if( $key == 'room_player_1' ){
                        $temp['xu'] = $room_info['room_player_2'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_3'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }else if( $key == 'room_player_2' ){
                        $temp['xu'] = $room_info['room_player_3'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_1'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }else if( $key == 'room_player_3' ){
                        $temp['xu'] = $room_info['room_player_1'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_2'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }
                    $temp['zjs']        = $room_info['room_zjs'];//添加总局数信息
                    $temp['room_mtype'] = $room_info['room_mtype'];//下划线隔开的玩法
                    $data['log_data'] = json_encode( $temp );
                    $db_connect->insert( PHZ_Log::__gTn( $room_id ) )->cols( $data )->query();
                    PHZ_Card::__update_MAX_HeaderID( $room_info , $value , $db_connect );//更新用户的当前最大可执行ID
                }
            }
        }
    }

    /**
     * 用户成功加入后，进行实时检查；如果人数已经满了；直接进行开始游戏
     * @param $room_id
     * @param $db_connect
     */
    public static function __J_Begin( $room_id  , $default_js ,  $db_connect ){
        $room_info = self::__getRoomInfo_byID( $room_id , $db_connect );
        if( $room_info['room_player_1'] > 0 && $room_info['room_player_2'] > 0 && $room_info['room_player_3'] > 0 ){
            //更新房间信息，设置开始局数,默认开始局数为1
            $cols = array();
            $cols['room_status'] = 1;//游戏进行中
            $cols['room_js']     = $default_js;//局数
            $cols['p1_start'] = 1;
            $cols['p2_start'] = 1;
            $cols['p3_start'] = 1;//三位玩家游戏状态设置为已准备
            $db_connect->update('tt_room')->cols( $cols )->where('room_id=' . $room_id )->query();
            //设置记录4人的牌面信息临时变量，方便进行提牌检查
            $card_temp = array();
            //获得一份牌面数据
            $pai = PHZ_Card::__C_Pai( PHZ_User::__get_user_Room_Index( $room_info , $room_info['banker'] ) );
            foreach( $room_info as $key => $value ){
                if( strstr($key,'room_player_') != false && $value != 0 ){
                    $data = array();
                    $temp = array();
                    /* 普通信息 */
                    $data['log_rid']    = $room_id;
                    $data['log_jid']    = $default_js;
                    $data['log_md']     = 15;//为房间消息
                    $data['log_uid']    = 888;//888为系统消息
                    $data['log_to_uid'] = $value;
                    /* 头像信息 */
                    $temp['pl'] = 1;//游戏操作类型，1：开局
                    $temp['mp'] = $key;//我是几P。。
                    $temp['mu'] = $value;
                    $temp['mn'] = PHZ_Member::__getFieldBy_ID( $value , 'name' , $db_connect );
                    $temp['mf'] = "";
                    $temp['xf'] = "";$temp['df'] = "";$temp['sf'] = "";
                    if( $key == 'room_player_1' ){
                        $temp['xu'] = $room_info['room_player_2'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_3'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }else if( $key == 'room_player_2' ){
                        $temp['xu'] = $room_info['room_player_3'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_1'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }else if( $key == 'room_player_3' ){
                        $temp['xu'] = $room_info['room_player_1'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                        $temp['su'] = $room_info['room_player_2'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                    }
                    /* 手牌信息 */
                    $temp['put_uid']    = $room_info['banker'];//庄家ID（创建的时候是创建本人；代开情况下；为第一个进入房间的人）
                    $temp['mop_uid']    = 0;//设置摸牌权
                    $temp['p1_sp']      = $pai['player_1'];//手牌
                    $temp['p1_lipai']   = PHZ_LiPai::__lipai( $pai['player_1'] , false , $room_info );
                    $temp['p2_lipai']   = PHZ_LiPai::__lipai( $pai['player_2'] , false , $room_info );
                    $temp['p3_lipai']   = PHZ_LiPai::__lipai( $pai['player_3'] , false , $room_info );
                    $temp['p2_sp']      = $pai['player_2'];
                    $temp['p3_sp']      = $pai['player_3'];
                    $temp['p1_dp']      = "";//底牌
                    $temp['p2_dp']      = "";
                    $temp['p3_dp']      = "";
                    $temp['p1_bp']      = "";//不要的牌
                    $temp['p2_bp']      = "";
                    $temp['p3_bp']      = "";
                    $temp['p1_xp']      = "";//吃，碰，跑起的牌
                    $temp['p2_xp']      = "";//吃，碰，跑起的牌
                    $temp['p3_xp']      = "";//吃，碰，跑起的牌
                    $temp['zjs']        = $room_info['room_zjs'];//添加总局数信息
                    $temp['room_mtype'] = $room_info['room_mtype'];//下划线隔开的玩法
                    $data['log_data']   = json_encode( $temp );
                    $db_connect->insert( PHZ_Log::__gTn( $room_id ) )->cols( $data )->query();
                    PHZ_Card::__update_MAX_HeaderID( $room_info , $value , $db_connect );//更新用户的当前最大可执行ID
                    //将每个人的牌面信息，存入到card表中，默认为第一局
                    $data = array();
                    $data['rid'] = $room_id;
                    $data['uid'] = $value;
                    $data['jid'] = $default_js;//局数
                    $data['zid'] = $room_info['banker'];//庄家ID
                    $data['dp']  = $pai['dipai'];//底牌
                    $data['sp']      = $pai['player_' . str_replace('room_player_','',$key) ];//默认手牌
                    $data['init_sp'] = $data['sp'];
                    $db_connect->insert('tt_room_card')->cols( $data )->query();
                    //将手牌信息置入临时数组
                    array_push( $card_temp , $data );
                }
            }
            //设置出牌权
            PHZ_Room::__setThisPutUser( $room_id , $room_info['banker'] , $db_connect );
            //更新房间缓存信息
            PHZ_Memcache::__set_RoomInfo_ToMemcache( $room_info );
            //进行起手提牌检查
            $tichkCount = PHZ_Card::_J_Begin_After_TICHK( $card_temp , $room_info , $room_info['room_js'] , $db_connect );
            //进行起手胡的检查（这里的起手胡只针对庄家)
            PHZ_Card::__J_Begin_HUpaiCHK( $room_id , $room_info ,  $room_info['banker'] , $tichkCount , $db_connect );
            //如果当前为第一局的情况下；更新下room里面的四个人的用户名信息，用于机器人提示人满时候的@使用
            if( $default_js == 1 ){
                self::__update_room_uname( $room_id , $db_connect , $room_info['room_player_1'] , $room_info['room_player_2'] , $room_info['room_player_3'] );
            }
            //返回确认开始
            return true;
        }
        return false;
    }

    /**
     * 更新room里面的uname信息
     * @param $room_id
     * @param $db_connect
     * @param int $uid_1
     * @param int $uid_2
     * @param int $uid_3
     * @param int $uid_4
     * @return mixed
     */
    public static function __update_room_uname( $room_id , $db_connect , $uid_1 = 0 , $uid_2 = 0 , $uid_3 = 0 ){
        $uname = "";
        if( $uid_1 != 0 ){
            $uname .= "@" . urldecode( PHZ_Member::__getFieldBy_ID( $uid_1 , "name" , $db_connect ) );
        }
        if( $uid_2 != 0 ){
            $uname .= " @" . urldecode( PHZ_Member::__getFieldBy_ID( $uid_2 , "name" , $db_connect ) );
        }
        if( $uid_3 != 0 ){
            $uname .= " @" . urldecode( PHZ_Member::__getFieldBy_ID( $uid_3 , "name" , $db_connect ) );
        }
        $uname = urlencode( $uname );
        return $db_connect->update('tt_room')->cols( array('uname'=> $uname ) )->where('room_id=' . $room_id )->query();
    }

    /**
     * 清除所有吃碰信息
     * @param $room_id
     * @param $db_connect
     */
    public static function __clear_chi_AND_peng( $room_id  , $db_connect ){
        $db_connect->update('tt_room')->cols( array('p1_is_chi'=>0,'p2_is_chi'=>0,'p3_is_chi'=>0,'p4_is_chi'=>0,'p1_is_peng'=>0,'p2_is_peng'=>0,'p3_is_peng'=>0,'p4_is_peng'=>0,) )->where('room_id=' . $room_id )->query();
    }

    /**
     * 设置当前的出牌人以及出牌号；以及是否清空当前的出牌人以及出牌号
     * @info::::出牌的时候需要增加；牌每人要或者牌被吃掉碰掉后；该参数需要归0；；；；；；结算后，这个也要执行一次
     * @param $uid
     * @param $card_number
     * @param $is_clear
     */
    public static function __setThisPutCard( $room_id , $uid , $card_number , $is_clear , $db_connect ){
        $cols = array();
        if( $is_clear == true ){
            $cols['tp_uid']  = 0;
            $cols['tp_card'] = 0;
        }else{
            $cols['tp_uid']  = $uid;
            $cols['tp_card'] = $card_number;
        }
        return $db_connect->update('tt_room')->cols( $cols )->where('room_id=' . $room_id )->query();
    }

    /**
     * 同上方：摸牌
     * @param $room_id
     * @param $uid
     * @param $card_number
     * @param $is_clear
     * @param $db_connect
     */
    public static function __setThisMopCard( $room_id , $uid , $card_number , $is_clear , $db_connect ){
        $cols = array();
        if( $is_clear == true ){
            $cols['tm_uid']  = 0;
            $cols['tm_card'] = 0;
        }else{
            $cols['tm_uid']  = $uid;
            $cols['tm_card'] = $card_number;
        }
        return $db_connect->update('tt_room')->cols( $cols )->where('room_id=' . $room_id )->query();
    }

    /**
     * 设置当前出牌权是谁？？？？？ + 同时设置一次timer指针
     * @param $room_id
     * @param $uid
     * @param $db_connect
     */
    public static function __setThisPutUser( $room_id , $uid , $db_connect ){
        return $db_connect->update('tt_room')->cols( array('this_put' => $uid , 'this_timer' => $uid ) )->where('room_id=' . $room_id )->query();
    }

    /**
     * 设置状态
     * @param $room_info
     * @param $user_id
     * @param $type     类型 hu peng  chi
     * @param $status   0 或者 1
     * @param $db_connect
     * @return mixed
     */
    public static function __setStatus( $room_info , $user_id , $type , $status , $db_connect ){
        $user_index = PHZ_Tools::__get_user_in_room_index( $room_info , $user_id );
        $p_index    = "p". $user_index ."_";
        return $db_connect->update('tt_room')->cols(array( $p_index . "is_" . $type => $status  ))->where('room_id = '. $room_info['room_id']  )->query();
    }
}